package com.bigShen.mybatis.exector;

import com.bigShen.use.entity.UserInfo;

import java.sql.*;

/**
 * @Author eddy.shen
 * @Date 2018/12/8 21:04
 **/
public class SimpleExecutorShen implements Executor {


    @Override
    public <T> T selectOne(String sql, Object parameter) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, String.valueOf(parameter));
            resultSet = preparedStatement.executeQuery();
            UserInfo userInfo = new UserInfo();
            while (resultSet.next()) {
                userInfo.setUser_name(resultSet.getString("USER_NAME"));
                userInfo.setPassword(resultSet.getString("PASSWORD"));
                userInfo.setAccount(resultSet.getString("ACCOUNT"));
            }
            return (T) userInfo;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(resultSet, preparedStatement, connection);
        }

        return null;
    }

    Connection getConnection() throws SQLException {

       return DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:HTBK", "TRD_CAMS", "xpar");

    }

    void closeAll(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {

        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != preparedStatement) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
